import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Card, Icon, Button, message, Modal, Popover, Progress, Row, Col, List, Alert, Tooltip } from 'antd';
import { queryTask } from '../../../services/task';

@connect(state => ({
  currentUser: state.user.currentUser,
  visible: state.modal.publishModal.visible,
  currentKey: state.modal.publishModal.currentKey,
  taskList: state.modal.publishModal.taskList,
  version: state.modal.publishModal.version,
  wetaoUser: state.user.wetaoUser,
}))

export default class PublishModal extends PureComponent {
  state = {
    percent: 0,
    errorCount: [],
    total: 0,
    current: 1,
    listData: [],
    errorMsg: '',
    disabled: false,
    publishStart: false,
    publishType: 'submit', // submit draft
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.currentKey === nextProps.k) {
      if (!this.props.visible && nextProps.visible) {
        this.setState({
          listData: nextProps.taskList,
          total: nextProps.taskList.length,
          disabled: false,
        });
        const nicaiCrx = document.getElementById('nicaiCrx');
        nicaiCrx.addEventListener('publishResult', this.publishResult);
        this.handleGetWetaoUser();
      } else if (this.props.visible && !nextProps.visible) {
        const nicaiCrx = document.getElementById('nicaiCrx');
        nicaiCrx.removeEventListener('publishResult', this.publishResult);
        this.setState({
          listData: [],
          total: 0,
          current: 1,
          percent: 0,
          errorMsg: '',
          errorCount: [],
          publishStart: false,
        });
      }
    }
  }
  handleGetWetaoUser = () => {
    const nicaiCrx = document.getElementById('nicaiCrx');
    const data = {
      url: 'https://we.taobao.com/account/getAccountSettingInfo.json?__version__=3.0',
      type: 'GET',
      actionName: 'setWetaoUser'
    };
    nicaiCrx.innerText = JSON.stringify(data);
    const customEvent = document.createEvent('Event');
    customEvent.initEvent('taobaoRequest', true, true);
    nicaiCrx.dispatchEvent(customEvent);
  }
  publishResult = (e) => {
    const data = JSON.parse(e.target.innerText);
    console.log(data);
    const { listData, total, current, publishType } = this.state;
    message.destroy();
    if (data.error) {
      message.error(data.msg);
      this.handlePublishError(data.msg);
    } else {
      if (total > current) {
        this.handlePublish(listData[current]);
      } else if (total === current) {
        if (publishType === 'submit') {
          message.success('发布成功');
        } else if (publishType === 'draft') {
          message.success('保存成功');
        }
      }
      const percent = parseInt((current / total) * 100);
      this.setState({
        current: total > current ? current + 1 : current,
        percent,
        // disabled: total === current ? false : true,
      });
    }
  }
  handlePublishError = (errorMsg) => {
    const { listData, errorCount, current, total } = this.state;
    errorCount.push({ index: current - 1, errorMsg: errorMsg });
    if (total > current) {
      setTimeout(() => {
        this.handlePublish(listData[current]);
      }, 1000);
    }
    const percent = parseInt((current / total) * 100);
    this.setState({
      percent,
      errorMsg: errorMsg,
      current: total > current ? current + 1 : current,
      // disabled: total === current ? false : true,
    });
  }
  handlePublish = async (task) => {
    const { version, wetaoUser } = this.props;
    if (version && version.length > 0) {
      const arr = version.split('.');
      const versionNumber = Number(arr[0]) * 100 + Number(arr[1]) * 10 + Number(arr[2]);
      if (versionNumber < 126) { // 1.0.4
        message.destroy();
        message.warn('请更新插件！');
        this.handlePublishError('请更新插件！');
      } else if (wetaoUser && wetaoUser.type !== '微淘号·达人') {
        message.destroy();
        message.warn('当前发布仅支持账号状态为"微淘号·达人"，请在阿里创作平台将登录账户切换至达人状态后，重新执行发布操作。');
        this.setState({ publishStart: false });
      } else {
        const result = await queryTask({
          _id: task._id,
        });
        this.handlePublishToTaobao(result.task);
      }
    } else {
      message.destroy();
      message.warn('请安装尼采创作平台插件！', 5);
      this.handlePublishError('请安装尼采创作平台插件！');
    }
  }
  handlePublishToTaobao = (task) => {
    let formData = {
      "template": "video2",
      "owner": "undefined",
      "formName": "",
      "activityName": "",
      "source": "creator",
      "userRole": "daren",
      "publishToolbar": "[{\"text\":\"发布新微淘\"},{\"text\":\"短视频(新)\"}]"
    }
    let channel_name = '微淘'
    if(task.channel_name === '短视频脚本') {
      task.formData = formData
      task.children = task.children.slice(3)
      task.channel_name = '微淘'
    }
    const { currentUser } = this.props;
    const nicaiCrx = document.getElementById('nicaiCrx');
    nicaiCrx.innerText = JSON.stringify({ task: task, user: currentUser, channel_name: task.channel_name, publishType: this.state.publishType });
    const customEvent = document.createEvent('Event');
    customEvent.initEvent('publishToTaobao', true, true);
    nicaiCrx.dispatchEvent(customEvent);
  }
  handleCancel = () => {
    this.props.dispatch({
      type: 'modal/hidePublish',
    });
    if (this.props.onOk) this.props.onOk();
  }
  renderListItem = (item, index) => {
    const { total, current, errorCount, percent } = this.state;
    let publishStatus = true;
    let backgroundColor = 'none';
    const errorItem = errorCount.find(item => item.index === index);
    if (errorItem) {
      publishStatus = false;
      backgroundColor = '#fff1f0';
    } else if (current - 1 > index || (percent === 100 && total === current && current > index)) {
      backgroundColor = '#f6ffed';
    }
    return (
      <List.Item style={{ background: backgroundColor }}>
        <span style={{ width: 80 }}>{item.id}</span>
        <span>{item.name}</span>
        <span>
          { !publishStatus ?
            <Tooltip placement="top" title={errorItem.errorMsg}>
              <Icon type="question-circle-o" style={{ marginLeft: 20 }} />
            </Tooltip> :
            ''
          }
        </span>
      </List.Item>
    );
  }
  handleStartPublish = () => {
    this.setState({
      publishStart: true,
      disabled: true,
      publishType: 'submit',
      errorCount: [],
      errorMsg: '',
    }, () => {
      if (this.props.taskList.length > 0) this.handlePublish(this.props.taskList[0]);
    });
  }
  handleSaveDraft = () => {
    this.setState({
      publishStart: true,
      disabled: true,
      publishType: 'draft',
      current: 1,
      percent: 0,
      errorMsg: '',
      errorCount: [],
    }, () => {
      if (this.props.taskList.length > 0) this.handlePublish(this.props.taskList[0]);
    });
  }
  render() {
    const { visible, k, currentKey, wetaoUser } = this.props;
    const { percent, current, total, errorMsg, errorCount, disabled, publishStart } = this.state;
    let status = 'active';
    let type = 'warning';
    let msg = `共${total}篇`;
    if (percent === 100) {
      msg = `完成，有${total - errorCount.length}篇成功，${errorCount.length}篇失败`;
      if (errorCount.length === 0) {
        type = 'success';
      }
      status = 'success';
    } else if (publishStart) {
      msg = `共${total}篇，当前第${current}篇，请勿离开`;
    }
    let title = '发布';
    if (wetaoUser.type) {
      title = `${title} （${wetaoUser.type ? wetaoUser.type : ''}`;
      title = `${title} ${wetaoUser.name ? wetaoUser.name : ''}）`;
    }
    return (
      <Modal
        width={800}
        // visible={true}
        visible={visible && currentKey === k}
        title={title}
        onCancel={this.handleCancel}
        maskClosable={false}
        closable={!publishStart || percent === 100}
        footer={<div>
          <Button disabled={disabled} onClick={this.handleSaveDraft}>保存到创作平台</Button>
          <Button
            disabled={disabled}
            onClick={this.handleStartPublish}
            type="primary"
          >
            发布到创作平台
          </Button>
          </div>}
      >
        <Row gutter={10}>
          <Col span={12} style={{ textAlign: 'center' }}>
            <Alert
              message={msg}
              type={type}
              style={{ textAlign: 'left', marginBottom: 30 }}
            />
            <div style={{ width: 200, height: 200, margin: 'auto', position: 'relative' }}>
              <Progress width={200} type="circle" percent={percent} status={status} />
            </div>
          </Col>

          <Col span={12}>
            <div style={{ height: 300, overflow: 'auto' }}>
              <List
                style={{ minHeight: 300 }}
                size="small"
                bordered
                dataSource={this.state.listData}
                renderItem={(item, index) => this.renderListItem(item, index)}
              />
            </div>
          </Col>
        </Row>
      </Modal>
    );
  }
}
